package com.gfl.trivialrestclient.controllers.forms;

import java.util.ArrayList;
import java.util.List;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * Class for mapping simplified version of Sprig BindingResult to JSON
 * 
 * @author Bedlam
 * 
 */
public class AjaxBindingResult {

	private String objectName;

	public class Error {
		private String fieldName;
		private String errorCode;
		private String defaultMessage;

		public Error(FieldError fieldError) {
			fieldName = fieldError.getField();
			errorCode = fieldError.getCode();
			defaultMessage = fieldError.getDefaultMessage();
		}

		public String getFieldName() {
			return fieldName;
		}

		public String getErrorCode() {
			return errorCode;
		}

		public String getDefaultMessage() {
			return defaultMessage;
		}

	}

	private List<Error> bindingErrors = new ArrayList<Error>();

	public AjaxBindingResult(BindingResult result) {
		objectName = result.getObjectName();

		bindingErrors = new ArrayList<Error>(result.getErrorCount());

		for (FieldError fieldError : result.getFieldErrors()) {
			bindingErrors.add(new Error(fieldError));
		}
	}

	public String getObjectName() {
		return objectName;
	}

	public List<Error> getBindingErrors() {
		return bindingErrors;
	}
}
